package cn.j0n4than.accountingtool.interceptor;

import cn.j0n4than.accountingtool.pojo.Auth;
import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 用户授权拦截器
 *
 * @author jonathan
 */
@Slf4j
@Component
public class AuthUserInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (token != null) {
            try {
                //解密Token
                String json = this.desUtil.decrypt(token);

                //将解密出来的json转换为Auth对象
                Auth auth = this.objectMapper.readValue(json, Auth.class);

                //记录
                log.info("AuthUserInterceptor:");
                log.info("授权:" + auth.toString());

                //查看redis里是否有这条数据
                log.error("redis: " + String.valueOf(redisUtil));
                String tokenInRedis = redisUtil.get(Integer.toString(auth.userId));
                if (tokenInRedis == null) {
                    log.info("redis中没有这条数据");
                    return unauthorized(response);
                }
                //如果用户传递的token和redis中的不一致
                if (!token.equals(tokenInRedis)) {
                    log.info("用户的token和redis中的token不一致");
                    return unauthorized(response);
                }

                //判断请求IP是否是token中的ip
                if (!request.getRemoteAddr().equals(auth.ip)) {
                    log.info("请求IP和Token中的IP不一致");
                    return unauthorized(response);
                }

                //检查授权的权限
                if (!auth.type.equals(Auth.TYPE_USER)) {
                    log.info("授权类型不匹配");
                    return unauthorized(response);
                }

                //检查token是否过期
                if ((new Date()).getTime() > auth.expire.getTime()) {
                    log.info("Token过期");
                    return unauthorized(response);
                }

                //验证授权成功
                //将授权信息设置到request attribute里面
                request.setAttribute("auth", auth);
                return true;
            } catch (RuntimeException e) {
                e.printStackTrace();
                log.error("解密Token失败");
                log.error(e.getMessage());
                return unauthorized(response);
            } catch (JsonMappingException e) {
                log.error("解密Token映射到Auth实体失败");
                log.error(e.getMessage());
                return unauthorized(response);
            }
        }

        log.error("请求没有传入Token");

        return unauthorized(response);
    }
}
